package com.tbvtc.agriculturalcreditchainserver2025.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.tbvtc.agriculturalcreditchainserver2025.comment.Token.JwtUtil;
import com.tbvtc.agriculturalcreditchainserver2025.dto.User.LoginByCaptchaDto;
import com.tbvtc.agriculturalcreditchainserver2025.dto.User.LoginByPasswordDto;
import com.tbvtc.agriculturalcreditchainserver2025.dto.User.UpdatePasswordDto;
import com.tbvtc.agriculturalcreditchainserver2025.entity.User;
import com.tbvtc.agriculturalcreditchainserver2025.exception.FoodException;
import com.tbvtc.agriculturalcreditchainserver2025.mapper.UserMapper;
import com.tbvtc.agriculturalcreditchainserver2025.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tbvtc.agriculturalcreditchainserver2025.utils.RUtils;
import com.tbvtc.agriculturalcreditchainserver2025.utils.Result;
import com.tbvtc.agriculturalcreditchainserver2025.utils.ResultCodeEnum;
import com.tbvtc.agriculturalcreditchainserver2025.constant.RedisConstant;
import com.tbvtc.agriculturalcreditchainserver2025.vo.UserVo;
import com.tbvtc.agriculturalcreditchainserver2025.vo.farmerVo.loginVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shiyuhao
 * @since 2025-03-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Resource(name = "redisTemplate1")
    private RedisTemplate stringRedisTemplate ;
    @Autowired
    private UserMapper userMapper;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public loginVo loginByPassword(LoginByPasswordDto loginDto) {
        User user = getOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, loginDto.getPhone())
        );
        if (user == null){
            throw new FoodException(ResultCodeEnum.USER_NOT_EXIST);
        }
        String password =  DigestUtil.md5Hex(loginDto.getPassword(), "UTF-8");
        if (!user.getPassword().equals(password)){
            throw new FoodException(ResultCodeEnum.APP_LOGIN_PHONE_ERROR);
        }

        Long userId = Long.valueOf(user.getId());
        String token = JwtUtil.createToken(loginDto.getPhone(), userId);
        return loginVo.builder()
                .id(userId)
                .token(token)
                .userImage(user.getUserImage())
                .roleId(user.getRoleId())
                .phone(user.getPhone())
                .build();

    }

    @Override
    public loginVo loginByCaptcha(LoginByCaptchaDto loginDto) {
        String captcha = (String) stringRedisTemplate.opsForValue().get(RedisConstant.APP_LOGIN_PREFIX+loginDto.getPhone());
        if (captcha == null){
            throw new FoodException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if (!loginDto.getCaptcha().equals(captcha)){
            throw new FoodException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        User user = getOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, loginDto.getPhone())
        );
        String token = JwtUtil.createToken(user.getPhone(), Long.valueOf(user.getId()));
        return
                loginVo.builder()
                        .id(Long.valueOf(user.getId()))
                        .token(token)
                        .roleId(user.getRoleId())
                        .userImage(user.getUserImage())
                        .phone(user.getPhone())
                        .build();
    }

    @Override
    public Result updatePassword(UpdatePasswordDto updatePassword) {
        User user = getOne(new LambdaQueryWrapper<User>()
                .eq(User::getPhone, updatePassword.getPhone())
        );
        if (user == null){
            return RUtils.Err(0,"用户不存在");
        }
        if (!user.getPassword().equals(DigestUtil.md5Hex(updatePassword.getOldPassword(), "UTF-8"))){
            return RUtils.Err(0,"旧密码错误");
        }
         if (!updatePassword.getNewPassword().equals(updatePassword.getConfirmPassword())){
             return RUtils.Err(0,"密码不一致");
         }

       update(new LambdaUpdateWrapper<User>()
                .eq(User::getPhone, updatePassword.getPhone())
                .set(User::getPassword, DigestUtil.md5Hex(updatePassword.getNewPassword(), "UTF-8"))
        );
         return RUtils.success();
    }

    @Override
    public Result getTokenTime(String  token) {
        try {
            Claims claims = JwtUtil.parseToken(token);
        } catch (FoodException e) {
            return RUtils.Err(0,"token过期");
        }
     return RUtils.success("token有效");

    }


}
